#!/usr/bin/python
# -*- coding:UTF8 -*-
from config import CrawlerData
import pandas as pd
import requests
import json
import sys

print(f'需要退出时输入0并回车'.center(23, '*'))
while True:
    into = input('请输入需要翻译的内容:')
    if into == '0':
        break
    else:
        # '_o'用了反爬虫机制，直接删除即可
        # url = 'https://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
        url = 'https://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
        user_agent = CrawlerData.user_agent_chrom
        r = requests.post(url=url, headers=user_agent).text
        # print(r)
        # jsondata = {}
        # jsondata['i'] = into
        # jsondata['from'] = 'AUTO'
        # jsondata['to'] = 'AUTO'
        # jsondata['doctype'] = 'json'
        # jsondata['client'] = 'fanyideskweb'
        jsondata = {'i': into, 'from': 'AUTO', 'to': 'AUTO', 'doctype': 'json', 'client': 'fanyideskweb'}
        r = requests.post(url=url, headers=user_agent, data=jsondata).text
        r = json.loads(r)
        # print(r)
        result = r['translateResult'][0][0]['tgt']
        print('请输出已经翻译的结果:' + r['translateResult'][0][0]['tgt'])
        data = pd.DataFrame({
            '输入': into,
            '结果': result
        }, index=[0])
        data.index = data.index + 1
        data.to_csv('./测试数据/TranslateResult.csv', index=0, header=0, encoding='ANSI', mode='a')
